import React, { useState, useEffect, useCallback } from 'react'
import '../assets/styles/pages/home.scss'
import { Layout} from 'antd'
import { connect } from 'react-redux'
import {logout} from '../store/user/actionCreators'
import { homeRouters } from '../router'
import { searchLeaves } from '../utils/common'
import HeaderUI from '../components/home/HeaderUI'
import SiderUI from '../components/home/SiderUI'
import ContentUI from '../components/home/ContentUI'
import { updateHistoryAction } from '../store/page/actionCreators'


const Home = (props) => {
  const {userState, doLogoout, history, updateHistoryAction} = props

  const [homeRoutes, setHomeRoutes] = useState([])
  const [title, setTitle] = useState('')
  const [defaultSelect, setDefaultSelect] = useState('/main')
  const [openKey, setOpenKey] = useState('/main')

  useEffect(() => {
    updateHistoryAction(history)
    setHomeRoutes(searchLeaves(homeRouters))
  }, [])

  useEffect(() => {
    const pathname = history.location.pathname
    console.log('pathname change', pathname, homeRoutes)
    // 找出title
    const currentRouter = homeRoutes.find(item => item.path === pathname)
    setTitle(currentRouter ? currentRouter.title : '')
    // 设置展开
    if (currentRouter && currentRouter.parentPath) setOpenKey(currentRouter.parentPath)
    // 设置默认选择
    setDefaultSelect(pathname)
  }, [history.location.pathname, homeRoutes])
  
  // 登出
  const handleLogout = useCallback(() => {
    doLogoout()
    history.push('/login')
  }, [doLogoout, history])
  
  const onOpenChange = useCallback(keys => {
    // console.log(keys)
    setOpenKey(keys[1])
  }, [])

  const handleLevel1Click = useCallback(() => {
    setOpenKey('/main')
  }, [])

  const toHome = useCallback(() => {
    setOpenKey('/main')
  }, [])
  return (
    <div className="page-home">
      <Layout>
        <HeaderUI
          toHome={toHome}
          title={title}
          userName={userState.user.name}
          handleLogout={handleLogout}
        ></HeaderUI>
        <Layout className="main-layout">
          <SiderUI
            curSelect={defaultSelect}
            onOpenChange={onOpenChange}
            openKey={openKey}
            routers={homeRouters}
            handleLevel1Click={handleLevel1Click}
          ></SiderUI>
          <ContentUI
            routes={homeRoutes}
          ></ContentUI>
        </Layout>
      </Layout>
    </div>
  )
}

// redux

const stateToProps = (state, props) => ({
  ...props,
  ...state
})

const actionToProps = {
  doLogoout: logout,
  updateHistoryAction
}

export default connect(stateToProps, actionToProps)(Home)
